package com.wannengbang.storemobile.homepage;


import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.wannengbang.storemobile.R;
import com.wannengbang.storemobile.base.BaseActivity;
import com.wannengbang.storemobile.base.DataCallBack;
import com.wannengbang.storemobile.bean.BaseResponseBean;
import com.wannengbang.storemobile.bean.ImageBean;
import com.wannengbang.storemobile.bean.ProductListBean;
import com.wannengbang.storemobile.event.ProductEvent;
import com.wannengbang.storemobile.homepage.model.HomePageModelImpl;
import com.wannengbang.storemobile.homepage.model.IHomePageModel;
import com.wannengbang.storemobile.utils.Base64BitmapUtil;
import com.wannengbang.storemobile.utils.CashierInputFilter;
import com.wannengbang.storemobile.utils.GlideEngine;
import com.wannengbang.storemobile.utils.GlideUtils;
import com.wannengbang.storemobile.utils.NumberFormatUtils;
import com.wannengbang.storemobile.utils.PermissionsManager;
import com.wannengbang.storemobile.utils.ToastUtil;
import com.wannengbang.storemobile.widget.AppTitleBar;
import com.wannengbang.storemobile.widget.ViewLoading;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ProductEditActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.iv_take_photo)
    ImageView ivTakePhoto;
    @BindView(R.id.edit_barcode)
    EditText editBarcode;
    @BindView(R.id.tv_scan)
    TextView tvScan;
    @BindView(R.id.edit_price)
    EditText editPrice;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    private ProductListBean.DataBean.ItemListBean itemListBean;
    private BottomSheetDialog selectPicDialog;
    private PermissionsManager permissionsManager;
    private String[] permissions;
    private int openType;//0 相册，1相机
    private List<LocalMedia> mediaList = new ArrayList<>();
    private IHomePageModel homePageModel;
    private String imgPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_product);
        ButterKnife.bind(this);
        initView();
    }

    public void initView() {
        InputFilter[] filters = {new CashierInputFilter()};
        editPrice.setFilters(filters);

        permissionsManager = new PermissionsManager(ProductEditActivity.this);
        homePageModel = new HomePageModelImpl();

        itemListBean = (ProductListBean.DataBean.ItemListBean) getIntent().getSerializableExtra("DataBean");

        imgPath = itemListBean.getThumb();

        editBarcode.setText(itemListBean.getCode());
        editName.setText(itemListBean.getName());
        String money = NumberFormatUtils.formatDouble(Double.parseDouble(itemListBean.getPrice()) / 100);
        editPrice.setText(money);

        if (!TextUtils.isEmpty(itemListBean.getThumb())) {
            GlideUtils.loadImage(mActivity, ivTakePhoto, itemListBean.getThumb());
        } else {
            ivTakePhoto.setImageResource(R.mipmap.ic_home_paizhao);
        }

    }

    @OnClick({R.id.iv_take_photo, R.id.tv_scan, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_take_photo:
                showPictureSelectorDialog();
                break;
            case R.id.tv_scan:
                IntentIntegrator integrator = new IntentIntegrator(mActivity);
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
                integrator.setOrientationLocked(false);
                integrator.setCaptureActivity(QRActivity.class);
                integrator.initiateScan();
                break;
            case R.id.tv_commit:
                String name = editName.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtil.showShort("请输入商品名称");
                    return;
                }
                String price = editPrice.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtil.showShort("请输入商品价格");
                    return;
                }
                String moneyUnit = String.valueOf(Double.parseDouble(price) * 100);
                moneyUnit = moneyUnit.substring(0, moneyUnit.indexOf("."));

                String code = editBarcode.getText().toString();

                requestStoreGoodsEdit(name, code, moneyUnit);
                break;
        }
    }

    public void requestStoreGoodsEdit(String name, String code, String price) {
        ViewLoading.showProgress(mActivity, "提交中...");
        homePageModel.requestStoreGoodsEdit(itemListBean.getId() + "", name, code, itemListBean.getStore_goods_category_id() + "", price, imgPath, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                EventBus.getDefault().post(new ProductEvent());
                ToastUtil.showShort("修改成功");
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    private void showPictureSelectorDialog() {

        selectPicDialog = new BottomSheetDialog(mActivity, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> handlerPhotoAlbumClick());
        camera.setOnClickListener(v -> handlerCameraClick());
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    /**
     * 点击相机
     */
    private void handlerCameraClick() {
        openType = 1;
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.CAMERA};

        if (PermissionsManager.checkPermissions(permissions)) {
            openCamera();
            cancelPictureDialog();
            return;
        }

        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openCamera();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 点击相册
     */
    private void handlerPhotoAlbumClick() {
        openType = 0;
        cancelPictureDialog();
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.READ_EXTERNAL_STORAGE};

        if (PermissionsManager.checkPermissions(permissions)) {
            openPhotoAlbum();
            cancelPictureDialog();
            return;
        }
        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(mActivity)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
        cancelPictureDialog();

    }

    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        PictureSelector.create(mActivity)//
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于20kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }

    @Override
    public void handlerPermissionForActivityResult() {
        if (PermissionsManager.checkPermissions(permissions)) {
            if (openType == 0) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else if (openType == 1) {
                openCamera();
                cancelPictureDialog();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                    if (mediaList.size() > 0) {
                        String imgPath = mediaList.get(0).getCompressPath();
                        requestUploadFile(imgPath);
                    }
                    break;
                case 49374:
                    //扫描结果回调
                    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                    if (result != null) {
                        if (result.getContents() == null) {
                            Toast.makeText(this, "扫描取消", Toast.LENGTH_LONG).show();
                        } else {
                            IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                            String code = scanResult.getContents();
                            editBarcode.setText(code);
                        }
                    }
                    break;
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 上传图片
     */
    public void requestUploadFile(String imgPaths) {
        ViewLoading.showProgress(mActivity, "上传中......");
        Bitmap bitmap = BitmapFactory.decodeFile(imgPaths);
        String file = Base64BitmapUtil.bitmapToBase64(bitmap);
        homePageModel.requestUploadFile("store", file, new DataCallBack<ImageBean>() {
            @Override
            public void onSuccessful(ImageBean bean) {
                ToastUtil.showShort("上传成功");
                imgPath = bean.getData().getUrl();
                GlideUtils.loadImage(mActivity, ivTakePhoto, bean.getData().getUrl());
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }
}
